const createError = require('http-errors');
const express = require('express');
// const bodyParser = require("body-parser");
const app = express();
const mongoose = require('mongoose')
const url = "mongodb://localhost:27017/movie";
const db = mongoose.connect(url, {
  useNewUrlParser: true
}, err => {
  if (err) throw err
  console.log('数据库连接成功')
})
const Movie = require('./schemas/schemas')

global.createResult = require('./utils/result')

const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method == "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
const movielist = require("./routes/web/movielist")
const movie = require('./routes/admin/movie');

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// app.use(bodyParser.json())
// app.use(bodyParser.urlencoded({ extended: true }));  

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//路由
app.use('/', movielist);
app.use('/admin', movie);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;